<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;

class Install extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('install')
            ->setDescription('the install command');
    }

    protected function execute(Input $input, Output $output)
    {
    	// 指令输出
        if(file_exists(root_path().'/database/install.lock')){
            $output->writeln('error: site installed,Please delete /database/install.lock file and try again');
            return;
        }
        $prefix = config('database.connections.mysql.prefix');
        $db_name = config('database.connections.mysql.database');
    	$output->writeln('install starting');
    	$create_db_sql = "CREATE DATABASE IF NOT EXISTS `{$db_name}` DEFAULT CHARACTER SET utf8mb4";
        $pdo = new \PDO("mysql:".config('database.connections.mysql.hostname').";",config('database.connections.mysql.username'),config('database.connections.mysql.password'));
    	if(!$pdo->exec($create_db_sql)){
            $output->writeln('create db fail');
            return;
        }
    	$sql = file_get_contents(root_path().'/database/install.sql');
        $sql = str_replace("\r", "\n", $sql);
        $sql = explode(";\n", $sql);
        $orginal = 'dd_';
        $sql = str_replace(" `{$orginal}", " `{$prefix}", $sql);
        $result = true;
        $error_sql = '';
        //开始安装
        foreach ($sql as $value) {
            $value = trim($value);
            if (empty($value)) {  continue; }
            if (false === Db::execute($value)) {
                $result = false;
                $error_sql = $value;
                break;
            }
        }
        if(!$result){
            $output->writeln('install fail');
            $output->writeln('error sql: '.$error_sql);
            return;
        }
        //创建管理员
        $res = Db::name('admin')->insert([
            'username'=>'admin',
            'nickname'=>'admin',
            'password'=>password_hash('123456',PASSWORD_DEFAULT),
            'create_time'=>time(),
            'update_time'=>time()
        ]);
        if(!$res){
            $output->writeln('create admin user fail');
            return;
        }
        file_put_contents(root_path().'/database/install.lock','');
        $output->writeln('install success');
    }
}
